const mongoClient = require('mongodb').MongoClient
const mongo = require('mongodb')
const config = require('../config/common_cfg')

const url = `mongodb://${ config.mongodb.user }:${ config.mongodb.pwd }@${ config.mongodb.host }:${config.mongodb.port}`
const dbName = config.mongodb.database
const ObjectID = mongo.ObjectID

class DB{
    static getInstance () {
        if(!DB.instance)DB.instance = new DB()
        return DB.instance
    }
    constructor () {
        this.connect
    }
    connect () {
        return new Promise((resolve, reject) => {
            mongoClient.connect(url, {useNewUrlParser: true, useUnifiedTopology: true}, (err, client) => {
                if(err){
                    console.log('连接错误:',err)
                    reject(err)
                }else{
                    console.log('连接成功')
                    const db = client.db(dbName)
                    resolve(db)
                }
            })
        })
    }
    insertOne (collectionName, data) {
        return new Promise((resolve, reject) => {
            this.connect().then( db => {
                db.collection(collectionName).insertOne(data, (err, res) => {
                    if(err)reject(err)
                    else resolve(res)
                })
            })
        })
    }
    update (collectionName, condition, new_data) {
        return new Promise( (resolve, reject) => {
            this.connect().then( db => {
                db.collection(collectionName).updateOne(condition, {$set: new_data}, (err, res) => {
                    if(err)reject(err)
                    else resolve(res)
                })
            })
        })
    }
    delete (collectionName, condition) {
        return new Promise( (resolve, reject) => {
            this.connect().then( db => {
                db.collection(collectionName).deleteOne(condition, (err, res) => {
                    if(err)reject(err)
                    else resolve(res)
                })
            })
        })
    }
    find (collectionName, condition, filter){
        return new Promise( (resolve, reject) => {
            this.connect().then( db => {
                db.collection(collectionName).find(condition).project(filter).toArray((err, res) => {
                    if(err)reject(err)
                    else resolve(res)
                })
            })
        })
    }
    aggregate(collectionName,pipeline){
        return new Promise( (resolve, reject) => {
            this.connect().then( db => {
                db.collection(collectionName).aggregate(pipeline).toArray((err, res) => {
                    console.log('pipeline:', pipeline)
                    if(err)reject(err)
                    else resolve(res)
                })
            })
        })
    }
    getObjectID (id) {
        return new ObjectID(id)
    }
}
module.exports = DB.getInstance()